package org.myrpc.rpc;


import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class RpcClientFactory implements BeanDefinitionRegistryPostProcessor,ApplicationContextAware{
	/*实现接口实现在spring中将对象注入和使用class标签定义*/
	
	private ApplicationContext applicationContext;
	
	//需要动态代理来实现创建的接口（即需要被管理的服务）
	private List<String> classNames;
	
	//zk的地址
	private String address;
	
	
	public List<String> getClassNames() {
		return classNames;
	}

	public void setClassNames(List<String> classNames) {
		this.classNames = classNames;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException {
		
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// TODO Auto-generated method stub
		this.applicationContext = applicationContext;
	}
	
	/*使用该方式*/
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		for(String className:classNames) {//遍历接口
			Class clazz = null;
			try {
				clazz = Class.forName(className);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//根据接口创建BeanDefinitionBuilder
			BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
			//通过构建对象获取GenericBeanDefinition
			GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();
			//注入接口
			definition.getPropertyValues().add("interfaceClass", definition.getBeanClassName());
			//注入服务地址
			definition.getPropertyValues().add("address", address);
			//注入工厂bean
			definition.setBeanClass(RpcProxyFactoryBean.class);
			//设置类型注入
			definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
			//注册bean
			registry.registerBeanDefinition(clazz.getSimpleName(),definition);
		}
	}

}
